using System;

namespace OpenWaves.ImageTransformations
{
    public class ScaleDownToFillTransformation : ImageTransformation
    {
        public ScaleDownToFillTransformation(int width, int height) : base(width, height)
        {
        }

        public ScaleDownToFillTransformation(string serializedProperties) : base(serializedProperties)
        {
        }

        public override void ApplyToImage(IImage image)
        {
            var widthRatio = (double)image.Width / Width;
            var heightRatio = (double)image.Height / Height;

            if (Math.Abs(widthRatio - heightRatio) > 0)
            {
                var ratio = Math.Min(widthRatio, heightRatio);

                var desiredWidth = ratio * Width;
                var desiredHeight = ratio * Height;

                var left = (image.Width - desiredWidth) / 2;
                var top = (image.Height - desiredHeight) / 2;

                image.Crop(Convert.ToInt32(left), Convert.ToInt32(top), Convert.ToInt32(desiredWidth),
                           Convert.ToInt32(desiredHeight));
            }

            if (image.Width > this.Width || image.Height > this.Height)
            {
                image.Scale(Width, Height);
            }
        }

        protected override IImageTransformation Scale(int width, int height)
        {
            return new ScaleDownToFillTransformation(width, height);
        }
    }
}